from django.shortcuts import render
#导包
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from django.contrib.auth import login
from oauth.models import OAuthQQUser

from django.db import DatabaseError
import json, re
from django_redis import get_redis_connection
from users.models import User

from meiduo_mall.utils.secret import SecretOauth
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.


#提供QQ登录页面网址
class QQURLView(View):
    def get(self, request):
        #next表示从哪个页面进入到的登录页面
        next = request.GET.get('next')
        # 将来登录成功后，就自动回到那个页面
        # 获取QQ登录页面网址
        # 创建OAuthQQ类的对象
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        #调用对象的获取qq地址方法
        login_url = oauth.get_qq_url()
        #返回登录地址
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})



#用户扫码登录的回调处理
class QQUserView(View):

    #Oauth2.0认证
    def get(self, request):
        #获取前端发送过来的code参数
        code = request.GET.get('code')
        #判断code参数是否存在
        try:
            # １、创建工具对象
            oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                            client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI,
                            state="/")
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '用户qq验证失败！'})

        try:
            qq_user = OAuthQQUser.objects.get(
                openid=openid
            )
        except OAuthQQUser.DoesNotExist as e:
            #加密openid
            auth = SecretOauth()
            access_token = auth.dumps({'openid': openid})
            return JsonResponse({
                'code': 300,
                'errmsg': 'ok',
                'access_token': access_token
            })
        else:
            #构建响应（绑定过）
            login(request, qq_user.user)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('usernmae', qq_user.user.username, max_age=14*24*60)
            #cookie和redis数据合并
            response = merge_cart_cookie_to_redis(request,response)
            return response

    #美多商城用户绑定到openid
    def post(self, request):
        #1、接收参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        #2、校验参数
        if not all([mobile, password, sms_code, access_token]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        #3、判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号码'})
        #4、判断密码是否合格
        if not re.match(r'^[0-9a-zA-Z_]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '请输入８－２０位的密码'})
        if not re.match(r'^\d{6}$', sms_code):
            return JsonResponse({'code': 400,'errmsg': 'sms_code格式有误！'})

        #5、判断短信验证码是否一样，创建redis连接对象
        conn = get_redis_connection('verify_code')
        #6、从redis中获取sms_code的值
        sms_code_from_redis = conn.get('sms_%s' % mobile)
        # 判断获取出来的有没有
        if not sms_code_from_redis:
            return JsonResponse({'code': 400, 'errmsg': '验证码失效'})
        #如果有，则进行判断
        if sms_code != sms_code_from_redis.decode():
            return JsonResponse({'code': 400, 'errmsg':'输入验证码失误'})

        #业务数据处理
        auth = SecretOauth()
        content_dict = auth.loads(access_token)
        if content_dict is None:
            return JsonResponse({'code': 400, 'errmsg': 'access_token无效'})
        openid = content_dict.get('openid')

        #保存注册数据
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            #根据手机号找不到－用户未注册美多账号
            #新建美多账号
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
            #绑定QQ
            OAuthQQUser.objects.create(
                user=user,
                openid=openid
            )
        else:
            #如果用户存在，检查用户密码
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '输入的密码不正确'})
        #将用户绑定openid
            OAuthQQUser.objects.create(openid=openid, user=user)
        #实现状态保持
        login(request, user)
        #创建响应对象
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        #登陆时用户名写入到cookie，有效期１４天
        response.set_cookie('username', user.username, max_age=3600*24*14)
        #cookie和redis数据合并
        response = merge_cart_cookie_to_redis(request, response)
        #构建响应
        return response